
import serial
import threading
import select
import redis
from util import logger
from setting import *

def singleton(cls): # 单例模式装饰器
    instance = None
    lock = threading.Lock()

    def get_instance(*args, **kwargs):
        nonlocal instance
        with lock:
            if not instance:
                instance = cls(*args, **kwargs)
            return instance
    return get_instance

@singleton
class SerialPortMethod: # 串口方法

    def __enter__(self):

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):

        self.ser.close()

    def __init__(self, serial_path="/dev/ttyS6", baud=115200):

        self.serial_path = serial_path

        self.ser = serial.Serial(self.serial_path, baud, 8, "N", timeout=0, stopbits=1)

        self.receive_thread = threading.Thread(target=self.receive_data)

        self.r = redis.Redis(host='localhost', port=6379, db=0)

        self.is_running = False

    def receive_data(self):

        self.is_running = True

        while self.is_running:
            if self.ser.in_waiting > 0:

                data = self.ser.read(self.ser.in_waiting)

                logger.info(data)

                self.r.rpush(STATION_ROW_DATA_STACK, data)

            select.select([self.ser], [], [], 0.1)

    def start_receive_thread(self):

        self.receive_thread.start()

    def stop_receive_thread(self):

        self.is_running = False

        self.receive_thread.join()

    def send_data(self, data: str):

        data = data.replace("\\r", "\r")


        print(data.encode('utf-8'))
        
        self.ser.write(data.encode('utf-8'))

    def send_row_data(self, row_command):
        
        self.ser.write(row_command)
    
    

if __name__ == "__main__":

    with SerialPortMethod() as ser:
        ser.receive_data()
        # 在此之后，你可以继续调用发送数据的方法，而监听线程会在后台一直运行并处理接收到的数据



